package com.clstu.reflection;

import com.clstu.cat.Cat;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

public class Reflection02 {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        f1();
        f2();
        f3();//根据测试结果是优化了之后时间节省1/3
    }
    //测试传统方法调用的时间
    public static void f1(){
        Cat cat = new Cat();
        long l = System.currentTimeMillis();//System.currentTimeMillis得到当前时间
        for (int i = 0; i < 900000000; i++) {
            cat.cry();
        }
        long l1 = System.currentTimeMillis();
        System.out.println("传统耗时====="+(l1-l));
    }
    //测试反射调用时间
    public static void f2() throws IOException, ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\re.properties"));
        String classfullpath = properties.getProperty("classfullpath");
        String method = properties.getProperty("method");
        Class cls = Class.forName(classfullpath);
        Object o = cls.newInstance();
        Method method1 = cls.getMethod(method);
        long l = System.currentTimeMillis();//System.currentTimeMillis得到当前时间
        for (int i = 0; i < 900000000; i++) {
            method1.invoke(o);
        }
        long l1 = System.currentTimeMillis();
        System.out.println("反射耗时====="+(l1-l));
    }
    //测试优化后的反射调用时间
    public static void f3() throws IOException, ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\re.properties"));
        String classfullpath = properties.getProperty("classfullpath");
        String method = properties.getProperty("method");
        Class cls = Class.forName(classfullpath);
        Object o = cls.newInstance();
        Method method1 = cls.getMethod(method);
        method1.setAccessible(true);//这个表示取消访问该方法时的安全检查
        long l = System.currentTimeMillis();//System.currentTimeMillis得到当前时间
        for (int i = 0; i < 900000000; i++) {
            method1.invoke(o);
        }
        long l1 = System.currentTimeMillis();
        System.out.println("反射(优化后)耗时====="+(l1-l));//优化就是取消方法调用时的安全检查
    }
}
